package com.example.chapter06;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.example.chapter06.util.FileUtil;
import com.example.chapter06.util.ToastUtil;

import java.io.File;

public class ImageWriteActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView iv_content;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_write);

        iv_content = findViewById(R.id.iv_content);
        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_read).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_save) {
            String fileName = System.currentTimeMillis() + ".jpeg";
            path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + File.pathSeparator + fileName;
            Log.d("ImageWriteActivity", "save jpeg path=" + path);
            Bitmap b1 = BitmapFactory.decodeResource(getResources(), R.drawable.ting2);
            FileUtil.saveImage(path, b1);
            ToastUtil.show(this, "图片已保存到" + path);

        } else if (v.getId() == R.id.btn_read) {
            // 方式一: 通过FileUtil工具类读取图片
//            Bitmap b2 = FileUtil.openImage(path);
//            iv_content.setImageBitmap(b2);
            // 方式二: 通过BitmapFactory工具类读取图片
//            Bitmap b3 = BitmapFactory.decodeFile(path);
//            iv_content.setImageBitmap(b3);
            // 方式三: 通过setImageURI方法读取图片
            iv_content.setImageURI(Uri.parse(path));
        }
    }
}